package cn.wit.summit.chwan.ui.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Display;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.wit.summit.chwan.R;
import cn.wit.summit.chwan.models.response.ResponseBase;
import cn.wit.summit.chwan.retrofit.ApiUtil;
import cn.wit.summit.chwan.retrofit.MyCallback;
import cn.wit.summit.chwan.retrofit.RetrofitManager;
import cn.wit.summit.chwan.tools.downloadtool.DownloadTool;
import cn.wit.summit.chwan.ui.base.MyActivity;
import cn.wit.summit.chwan.utils.AccountBean;
import cn.wit.summit.chwan.utils.AccountUtil;
import cn.wit.summit.chwan.utils.LogUtils;
import cn.wit.summit.chwan.utils.MD5Utils;
import cn.wit.summit.chwan.utils.MobileCodeUtils;
import cn.wit.summit.chwan.utils.NetWorkUtils;
import cn.wit.summit.chwan.utils.PreferenceUtil;
import cn.wit.summit.chwan.utils.RegularUtil;
import cn.wit.summit.chwan.utils.StringUtils;
import cn.wit.summit.chwan.utils.SystemInfoUtils;
import cn.wit.summit.chwan.widgets.SoftKeyBoardListener;
import retrofit2.Retrofit;

/**
 * Created by Alan on 2018/7/26.
 */

public class LoginV2Activity extends MyActivity {

    @Bind(R.id.loginV2TabOneTv)
    TextView loginV2TabOneTv;
    @Bind(R.id.loginV2TabTwoTv)
    TextView loginV2TabTwoTv;
    @Bind(R.id.loginV2TopRl)
    RelativeLayout loginV2TopRl;
    @Bind(R.id.loginV2MessagePhoneNumEt)
    EditText loginV2MessagePhoneNumEt;
    @Bind(R.id.loginV2MessageGetCodeTx)
    TextView loginV2MessageGetCodeTx;
    @Bind(R.id.loginV2MessageCodeEt)
    EditText loginV2MessageCodeEt;
    @Bind(R.id.dialogMessageLoginBt)
    Button dialogMessageLoginBt;
    @Bind(R.id.loginV2BottomOneLl)
    LinearLayout loginV2BottomOneLl;
    @Bind(R.id.loginV2PasswordPhoneNumEt)
    EditText loginV2PasswordPhoneNumEt;
    @Bind(R.id.loginV2PasswordPWEt)
    EditText loginV2PasswordPWEt;
    @Bind(R.id.dialogPasswordLoginBt)
    Button dialogPasswordLoginBt;
    @Bind(R.id.loginV2BottomTwoLl)
    LinearLayout loginV2BottomTwoLl;
    @Bind(R.id.loginV2TopIv)
    ImageView loginV2TopIv;
    @Bind(R.id.loginV2TopTwoIv)
    ImageView loginV2TopTwoIv;
    @Bind(R.id.loginV2BackIv)
    ImageView loginV2BackIv;
    @Bind(R.id.loginV2TitleTv)
    TextView loginV2TitleTv;
    @Bind(R.id.loginV2RootLl)
    LinearLayout loginV2RootLl;

    private int topHeight;
    private int tabSelectId = 1;
    private String phone = "";
    private int time = 60;

    private RetrofitManager retrofitManager;
    private Retrofit retrofitLogin;
    private ApiUtil apiLogin;

    private EditText getFousEt;

    private int disH = 150;
    private int disHeight = 0;
    private int tempHeight = 0;
    @SuppressLint("HandlerLeak")
    Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) loginV2RootLl.getLayoutParams();
                    params.topMargin = - disHeight;
                    loginV2RootLl.setLayoutParams(params);
                    tempHeight += 20;
                    if (tempHeight < disHeight) {
                        Message message = new Message();
                        message.what = 1;
                        handler.sendMessageDelayed(message, 50);
                    } else {
                        Message message = new Message();
                        message.what = 11;
                        handler.sendMessageDelayed(message, 50);
                    }
                    break;
                case 11:
                    RelativeLayout.LayoutParams paramsShow = (RelativeLayout.LayoutParams) loginV2RootLl.getLayoutParams();
                    paramsShow.topMargin = - disHeight;
                    loginV2RootLl.setLayoutParams(paramsShow);
                    break;
            }
            super.handleMessage(msg);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login_v2);
        ButterKnife.bind(this);

        hideTitleBar();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            topHeight = getStateBarHeight();
            RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, topHeight);
            loginV2TopIv.setLayoutParams(params);
            loginV2TopIv.setVisibility(View.VISIBLE);
            loginV2TopTwoIv.setLayoutParams(params);
            loginV2TopTwoIv.setVisibility(View.VISIBLE);
        }

        Display display = getWindowManager().getDefaultDisplay();
        int w = display.getWidth();
        int h = display.getHeight();

        if (h!=1920) {
            disH = disH * h /1920;
        }

        LinearLayout.LayoutParams paramsLl = new LinearLayout.LayoutParams(w, w*808/720);
        loginV2TopRl.setLayoutParams(paramsLl);

        retrofitManager = RetrofitManager.getInstance(mContext);
        retrofitLogin = retrofitManager.getLoginRetrofit();
        apiLogin = retrofitLogin.create(ApiUtil.class);

        getFousEt = loginV2MessagePhoneNumEt;

        loginV2MessageCodeEt.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                toLoginOne();
                return false;
            }
        });

        loginV2PasswordPWEt.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                toLoginTwo();
                return false;
            }
        });

//        new Handler().postDelayed(new Runnable() {
//            @Override
//            public void run() {
//                showInput();
//            }
//        }, 200);

        SoftKeyBoardListener.setListener(mAty, new SoftKeyBoardListener.OnSoftKeyBoardChangeListener() {
            @Override
            public void keyBoardShow(final int height) {
                disHeight = height-disH;
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        Message message = new Message();
                        message.what = 1;
                        handler.sendMessage(message);
                    }
                }, 100);
            }
            @Override
            public void keyBoardHide(int height) {
                disHeight = 0;
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) loginV2RootLl.getLayoutParams();
                        params.topMargin = 0;
                        loginV2RootLl.setLayoutParams(params);
                    }
                }, 100);
            }
        });
    }

    private void hidInput(View view) {
        hideSoftInput(view);
    }

    private void showInput() {
        showSoftInput(getFousEt);
    }

    @OnClick({R.id.loginV2TabOneTv, R.id.loginV2TabTwoTv, R.id.loginV2TopRl, R.id.loginV2MessageGetCodeTx
            , R.id.dialogMessageLoginBt, R.id.dialogPasswordLoginBt, R.id.loginV2BackIv})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.loginV2TabOneTv:
                changeTabs(1);
                break;
            case R.id.loginV2TabTwoTv:
                changeTabs(2);
                break;
            case R.id.loginV2TopRl:
                hidInput(view);
                break;
            case R.id.loginV2MessageGetCodeTx:
                //获取验证码
                if (NetWorkUtils.isNetworkConnected(mContext))
                    getVerification();
                else
                    showToast("网络连接失败，再试试吧~");
                break;
            case R.id.dialogMessageLoginBt:
                hidInput(view);
                toLoginOne();
                break;
            case R.id.dialogPasswordLoginBt:
                hidInput(view);
                toLoginTwo();
                break;
            case R.id.loginV2BackIv:
                hidInput(view);
                finish();
                break;
        }
    }

    private void changeTabs(int id) {
        tabSelectId = id;
        if (id == 1) {
            loginV2TabOneTv.setTextColor(getResources().getColor(R.color.color_101010));
            loginV2TabTwoTv.setTextColor(getResources().getColor(R.color.color_B1B1B1));
            loginV2BottomOneLl.setVisibility(View.VISIBLE);
            loginV2BottomTwoLl.setVisibility(View.GONE);
            phone = loginV2PasswordPhoneNumEt.getText().toString().trim();
            loginV2MessagePhoneNumEt.setText(phone);
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    getFousEt = loginV2MessagePhoneNumEt;
                    showInput();
                    loginV2MessagePhoneNumEt.setSelection(phone.length());
                }
            }, 100);
        } else {
            loginV2TabOneTv.setTextColor(getResources().getColor(R.color.color_B1B1B1));
            loginV2TabTwoTv.setTextColor(getResources().getColor(R.color.color_101010));
            loginV2BottomOneLl.setVisibility(View.GONE);
            loginV2BottomTwoLl.setVisibility(View.VISIBLE);
            phone = loginV2MessagePhoneNumEt.getText().toString().trim();
            loginV2PasswordPhoneNumEt.setText(phone);
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    getFousEt = loginV2PasswordPhoneNumEt;
                    showInput();
                    loginV2PasswordPhoneNumEt.setSelection(phone.length());
                }
            }, 100);
        }
    }

    /**
     * 获取验证码
     * 正则验证
     */
    private void getVerification() {
        String phoneNumber = loginV2MessagePhoneNumEt.getText().toString().trim();
        if (StringUtils.isNotEmpty(phoneNumber)) {
            if (RegularUtil.getIphoneCorrect(phoneNumber) == true) {
                time = 60;
                MobileCodeUtils.getCode(mAty, phoneNumber);
                loginV2MessageGetCodeTx.setText(60 + "s后重发");
                loginV2MessageGetCodeTx.setEnabled(false);
                setLoadTime();
                loginV2MessageCodeEt.setFocusable(true);
                loginV2MessageCodeEt.setFocusableInTouchMode(true);
                loginV2MessageCodeEt.requestFocus();
            } else {
                showToast("手机格式不正确");
            }
        } else {
            showToast("手机号码不能为空");
        }
    }

    private void setLoadTime() {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                --time;
                loginV2MessageGetCodeTx.setText("" + time + "s后重发");
                if (time == 0) {
                    time = 60;
                    loginV2MessageGetCodeTx.setEnabled(true);
                    loginV2MessageGetCodeTx.setText(getResources().getString(R.string.btn_yanzhenma));
                } else {
                    setLoadTime();
                }
            }
        }, 1000);
    }

    private void toLoginOne() {
        String phoneNumber = loginV2MessagePhoneNumEt.getText().toString().trim();
        String codeNumber = loginV2MessageCodeEt.getText().toString().trim();
        String shareCode = getShareCodeByWalle(); // 注册邀请码 有就上传，没有就传空字符。
        if (NetWorkUtils.isNetworkConnected(mContext)) {
            if (StringUtils.isNotEmpty(phoneNumber) && StringUtils.isNotEmpty(codeNumber)) {
                String imei = SystemInfoUtils.getInstance(mContext).getIMEI();
                if (StringUtils.isEmpty(imei)) {
                    checkAllPerm();
                    return;
                }

                apiLogin.getCodeLogin(phoneNumber, codeNumber, shareCode).enqueue(new MyCallback<ResponseBase<AccountBean>>() {
                    @Override
                    public void onSuccess(ResponseBase<AccountBean> model) {
                        AccountBean data = model.getData_info();
                        setSP(data);
                    }

                    @Override
                    public void onFailure(int code, String msg) {
                        showToast(msg);
                    }
                });
            } else {
                showToast("手机号或验证码为空");
            }
        } else {
            showToast("网络连接失败，再试试吧~");
        }
    }

    private void toLoginTwo() {
        String account = loginV2PasswordPhoneNumEt.getText().toString().trim();
        String pwd = loginV2PasswordPWEt.getText().toString().trim();
        if (account == null || account.equals("")) {
            showToast("账号不能为空");
            return;
        }
        if (pwd == null || pwd.equals("")) {
            showToast("密码不能为空");
            return;
        }
        if (pwd.length() < 6 || pwd.length() > 20) {
            showToast("密码长度低于6位或高于20位");
            return;
        }

        String newPwd = MD5Utils.encode(pwd);
        if (StringUtils.isNotEmpty(account) && StringUtils.isNotEmpty(newPwd)) {
            if (NetWorkUtils.isNetworkConnected(mContext)) {
                if (RegularUtil.getIphoneCorrect(account) == true) {
                    apiLogin.getAccountLogin(account, newPwd).enqueue(new MyCallback<ResponseBase<AccountBean>>() {
                        @Override
                        public void onSuccess(ResponseBase<AccountBean> model) {
                            AccountBean data = model.getData_info();
                            LogUtils.e(data.getToken());
                            setSP(data);
                        }

                        @Override
                        public void onFailure(int code, String msg) {
                            showToast(msg);
                        }
                    });
                } else {
                    showToast("手机号码格式不正确");
                }
            } else {
                showToast("网络连接失败，再试试吧~");
            }
        } else {
            showToast("账号或密码为空");
        }
    }

    private void setSP(AccountBean data) {

        LogUtils.e("codeToken:" + data.getToken());
        Log.e("TAG", data.getUid() + "|" + data.getToken());

        AccountUtil.getInstance().saveAccountData(data);

        int userId = PreferenceUtil.getIntPreferences(mContext, PreferenceUtil.PRE_USERID);
        if (AccountUtil.getInstance().getUid()!=userId) {
            MobileCodeUtils.taskStartAppTag(mContext);
            PreferenceUtil.saveLongPreference(mContext, PreferenceUtil.PRE_FIRST_SHARE, 0l);
            PreferenceUtil.saveLongPreference(mContext, PreferenceUtil.PRE_FIRST_DOWNLOAD, 0l);
            PreferenceUtil.saveLongPreference(mContext, PreferenceUtil.PRE_FIRST_START_APP, 0l);
            PreferenceUtil.saveIntPreference(mContext, PreferenceUtil.PRE_USERID, AccountUtil.getInstance().getUid());
        }

        if (data.getDefaultNickname() == 0 || data.getAvatar().contains("avatar_default")) {//未设置昵称
            Intent intent = new Intent(mContext, SetPersonalInformationActivity.class);
            Bundle bundle = new Bundle();
            bundle.putSerializable("login_data", data);
            intent.putExtras(bundle);
            startActivity(intent);
            finish();
            return;
        }

        showToast("登录成功");
        String gameid = PreferenceUtil.getPreferences(mContext, "toursEnergyPreGameID");
        if (StringUtils.isNotEmpty(gameid)) {
            DownloadTool.sendMessageEnergy(mContext, gameid);
        }
        Intent intent = new Intent(mContext, MainActivity.class);
        startActivity(intent);
        finish();
    }
}
